package cn.sumpu.app.guoguojie.biz.impl;



import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.guoguojie.biz.DetailBiz;
import cn.sumpu.app.guoguojie.dao.DetailDao;
import cn.sumpu.app.guoguojie.domain.Detail;
import cn.sumpu.app.guoguojie.domain.Personality;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;

public class DetailBizImpl implements DetailBiz {

	private DetailDao detailDao;
	
	
	public void setDetailDao(DetailDao detailDao) {
		this.detailDao = detailDao;
	}


	//查询个性化资料页面
	@Override
	public Detail getDetailById(String member)throws AppBusinessException {
		if(Common.empty(member)) return null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("member", member);
		List<Detail> detailList = detailDao.getDetailList(map);
		if(detailList!=null && detailList.size() > 0){
			Detail d = detailList.get(0);
			Map<String,Object> mapPer = new HashMap<String,Object>();
			mapPer.put("member", d.getMember());
			d.setPersonalityList(detailDao.getPersonalityList(mapPer));
			return d;
		}
		return null;
	}
	
	//查询会员的所有信息
	@Override
	public Detail getDetailAll(String member)throws AppBusinessException {
		if(Common.empty(member)) return null;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("member", member);
		Detail detail = detailDao.getDetailByMember(map);
		if(detail != null){
			detail.setPersonalityList(detailDao.getPersonalityList(map));
			detail.setWorkList(detailDao.getWorkList(map));
			detail.setLearningList(detailDao.getLearningList(map));
			detail.setContactList(detailDao.getContactList(map));
			return detail;
		}
		return null;
	}

	
	@Override
	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	public void saveDetail(Detail detail) throws AppBusinessException {
		if(detail==null) return ;
		Detail d = getDetailById(detail.getMember());
		if(d == null){
			detailDao.insertDetail(detail);
		}else{
			detailDao.updateDetail(detail);
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("member", detail.getMember());
		detailDao.deletePersonality(map);
		List<Personality> pList = detail.getPersonalityList();
		if(pList != null && pList.size() > 0){
			for (Personality personality : pList) {
				personality.setMember(detail.getMember());
				if(!Common.empty(personality.getName()) && !Common.empty(personality.getValue())){
					if(personality.getName().length()>50)
						personality.setName(personality.getName().substring(0, 49));
					if(personality.getValue().length()>500)
						personality.setValue(personality.getValue().substring(0, 499));
					detailDao.insertPersonality(personality);
				}
			}
		}
	}


	@Override
	public void updateDetail(Detail detail) throws AppBusinessException {
		detailDao.updateDetail(detail);
	}
	

}
